package com.ttctracker.xmlparser;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

/**
 * This a helper class that simplifies the process of parsing xml resources.
 * 
 * @author Wenbin
 * 
 */
public class SAXParserHelper {
	private Class<?> handlerClass;
	private ContentHandler handler;
	private SAXParserFactory factory;
	private SAXParser parser;
	private XMLReader xmlReader;
	private String url;
	private InputStream iStream;

	// InputSource iSource;

	public SAXParserHelper(Class<?> handlerClass) {
		this(null, handlerClass);
	}

	/**
	 * Constructor
	 * 
	 * @param inputeStream
	 *            -the inputStream of the xml resource (can be file or url)
	 * @param handlerClass
	 */
	public SAXParserHelper(InputStream iStream, Class<?> handlerClass) {
		// this.iSource=iSource;
		this.iStream = iStream;
		this.handlerClass = handlerClass;
	}

	/**
	 * Setup the parser
	 * 
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws SAXException
	 * @throws ParserConfigurationException
	 * @throws IOException
	 */
	public void setup_parser() throws IllegalAccessException,
			InstantiationException, SAXException, ParserConfigurationException,
			IOException {
		factory = SAXParserFactory.newInstance();

		// create a parser
		parser = factory.newSAXParser();

		// create the reader (scanner)
		xmlReader = parser.getXMLReader();

		if (handler == null) {
			// instantiate our parser
			handler = (ContentHandler) handlerClass.newInstance();
		}

		// assign our handler
		xmlReader.setContentHandler(handler);

	}

	/**
	 * Parse the input xml resource
	 * 
	 * @throws IOException
	 * @throws SAXException
	 */
	public void parseXml() throws IOException, SAXException {
		xmlReader.parse(new InputSource(iStream));
	}

	public ContentHandler getHandler() {
		return handler;
	}

	public void setHandler(ContentHandler handler) {
		this.handler = handler;
	}

	public SAXParser getParser() {
		return parser;
	}

	public XMLReader getXmlReader() {
		return xmlReader;
	}

	public InputStream getInputStream() {
		return iStream;
	}

	public void setInputStream(InputStream iStream) {
		this.iStream = iStream;
	}
}
